package com.juneyao.log.logcenter.scheduler;

import com.juneyao.log.logcenter.scheduler.mapping.IndexMapping;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author quanbiao
 * @date 2018-07-30
 * 定时新建：操作日志索引，应用日志索引
 * 添加别名
 */
@Component
public final class QuartzIndexService {

    private Logger logger = LoggerFactory.getLogger("QuartzIndexService");

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 应用日志索引前缀
     */
    @Value("${elasticsearch.application.index.name.prefix}")
    private String APPLICATION_LOG_INDEX_PREFIX;

    /**
     * 操作日志索引前缀
     */
    @Value("${elasticsearch.operate.index.name.prefix}")
    private String OPERATE_LOG_INDEX_PREFIX;

    /**
     * 定时新建应用，操作日志
     * 应用日志索引格式：log-application:2018-07-30
     * 操作日志索引格式：log-operate:2018-07-30
     * 添加别名
     * 每天晚上11点，新建明天的索引
     */
    @Scheduled(cron = "0 4 23 * * ?")
    public void createOperateOrAppIndex(){
        //获取明天的日期
        String tomorrowDay = new DateTime().plusDays(1).toString("yyyy-MM-dd");
        //提前创建明天的索引
        createIndexByDate(tomorrowDay);
    }

    /**
     * 创建索引并添加别名
     * @param elasticsearchTemplate
     * @param indexName 索引名称
     * @param aliasName 别名
     */
    private void createIndexAddAlias(ElasticsearchTemplate elasticsearchTemplate, String indexName, String aliasName){
        //创建索引
        elasticsearchTemplate.createIndex(indexName);
        //创建mapping
        if(indexName.startsWith(APPLICATION_LOG_INDEX_PREFIX)){
            elasticsearchTemplate.putMapping(indexName, "log", IndexMapping.applicationIndexMapping);
        }
        if(indexName.startsWith(OPERATE_LOG_INDEX_PREFIX)){
            elasticsearchTemplate.putMapping(indexName, "log", IndexMapping.operateIndexMapping);
        }
        //添加别名
        AliasQuery aliasQuery = new AliasQuery();
        aliasQuery.setIndexName(indexName);
        aliasQuery.setAliasName(aliasName);
        elasticsearchTemplate.addAlias(aliasQuery);
    }

    /**
     * 根据日期判断索引去创建索引
     * @param dateStr
     */
    private void createIndexByDate(String dateStr){
        //应用日志索引
        String appIndexName = APPLICATION_LOG_INDEX_PREFIX + dateStr;
        if(!elasticsearchTemplate.indexExists(appIndexName)){
            //创建索引并添加别名
            createIndexAddAlias(elasticsearchTemplate, appIndexName, "log-application");
            logger.info("应用日志索引：" + appIndexName + " 创建成功！！！");
        }
        //操作日志
//        String operateIndexName = OPERATE_LOG_INDEX_PREFIX + dateStr;
//        if(!elasticsearchTemplate.indexExists(operateIndexName)){
//            //创建索引并添加别名
//            createIndexAddAlias(elasticsearchTemplate, operateIndexName, "log-operate");
//            logger.info("操作日志索引：" + operateIndexName + " 创建成功！！！");
//        }
    }

    /**
     * 项目启动，初始化应用日志索引和操作日志索引
     */
    @PostConstruct
    private void initIndexName(){
        //获取今天的时间
        String todayStr = new DateTime().toString("yyyy-MM-dd");
        createIndexByDate(todayStr);
    }
}
